package com.answeringplayer.service.Impl;

import com.answeringplayer.Bean.Request;
import com.answeringplayer.Bean.Response;
import com.answeringplayer.domain.User;
import com.answeringplayer.dto.LoginDTO;
import com.answeringplayer.dto.UserDTO;
import com.answeringplayer.exception.BusinessException;
import com.answeringplayer.mapper.UserMapper;
import com.answeringplayer.service.CaptchaService;
import com.answeringplayer.service.LoginService;
import com.answeringplayer.utils.JwtTokenProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import static com.answeringplayer.constant.Constant.TOKEN_EXPIRE_TIME;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    @Autowired private CaptchaService captchaService;


    @Override
    public Response<LoginDTO> login(Request<UserDTO> request) {
        try {
            UserDTO userDTO = request.getData();

            // 参数验证
            if (userDTO.getUsername() == null || userDTO.getUsername().trim().isEmpty()) {
                throw new BusinessException(400, "用户名不能为空");
            }
            if (userDTO.getPassword() == null || userDTO.getPassword().trim().isEmpty()) {
                throw new BusinessException(400, "密码不能为空");
            }

            // 获取用户名和密码
            String userName = userDTO.getUsername();
            String password = userDTO.getPassword();

            // 查询数据库
            User user = null;
            try {
                user = userMapper.selectByUsername(userName);
            } catch (Exception e) {
                throw new BusinessException(500, "用户查询异常");
            }

            if (user == null) {
                throw new BusinessException(404, "用户不存在");
            }

            // 验证密码（注意：实际项目中密码应该是加密存储的）
            if (!user.getPassword().equals(password)) {
                throw new BusinessException(401, "用户名或密码错误");
            }

            // 生成 JWT 令牌
            String token = jwtTokenProvider.generateToken(user);

            LoginDTO loginResponse = setLoginDTO(userName, user, token);

            return Response.success("登录成功", loginResponse);

        } catch (BusinessException e) {
            // 业务异常直接抛出，由全局异常处理器处理
            throw e;
        } catch (Exception e) {
            // 其他异常包装为业务异常
            throw new BusinessException(500, "登录失败: " + e.getMessage());
        }
    }

    @Override
    public Response<LoginDTO> register(Request<UserDTO> request) {
        try {
            UserDTO userDTO = request.getData();

            // ========== 新增：验证码校验 ==========
            // 假设前端通过请求头传递 captcha-id 和 captcha
            String captchaId = userDTO.getCaptchaId();
            String captchaInput = userDTO.getCaptchaCode();

            // 也可以从 body 传（比如 UserDTO 新增字段 captchaId, captchaCode）
            // 这里以 header 为例

            if (captchaId == null || captchaInput == null || captchaInput.trim().isEmpty()) {
                throw new BusinessException(400, "验证码不能为空");
            }

            if (!captchaService.validateCaptcha(captchaId, captchaInput)) {
                throw new BusinessException(400, "验证码错误或已过期");
            }







            // 参数验证
            if (userDTO.getUsername() == null || userDTO.getUsername().trim().isEmpty()) {
                throw new BusinessException(400, "用户名不能为空");
            }
            if (userDTO.getPassword() == null || userDTO.getPassword().trim().isEmpty()) {
                throw new BusinessException(400, "密码不能为空");
            }
            // 用户名长度验证
            if (userDTO.getUsername().length() < 3 || userDTO.getUsername().length() > 20) {
                throw new BusinessException(400, "用户名长度应在3-20个字符之间");
            }
            // 密码长度验证
            if (userDTO.getPassword().length() < 6) {
                throw new BusinessException(400, "密码长度至少为6个字符");
            }

            // 检查用户名是否已存在
            try {
                User existingUser = userMapper.selectByUsername(userDTO.getUsername());
                if (existingUser != null) {
                    throw new BusinessException(400, "用户名已存在");
                }
            } catch (Exception e) {
                throw new BusinessException(500, "用户查询异常");
            }

            // 创建新用户
            User newUser = new User();
            newUser.setUsername(userDTO.getUsername());
            newUser.setPassword(userDTO.getPassword()); // 注意：实际项目中应该进行密码加密
            // Mock 场景：用 username 模拟 openid
            newUser.setOpenid("mock_"+userDTO.getUsername());
            // nickname 和 avatarUrl 可以为 null，由后续设置补充
            newUser.setNickname(null);
            newUser.setAvatarUrl(null);
//            newUser.setNickname(userDTO.getNickname() != null && !userDTO.getNickname().trim().isEmpty()
//                    ? userDTO.getNickname() : "用户" + userDTO.getUsername());
//            newUser.setAvatarUrl(userDTO.getAvatarUrl() != null && !userDTO.getAvatarUrl().trim().isEmpty()
//                    ? userDTO.getAvatarUrl() : "https://api.dicebear.com/7.x/avataaars/svg?seed=" + userDTO.getUsername());
            newUser.setConsecutiveDays(0);
            newUser.setTotalQuestionsAnswered(0);
            newUser.setCorrectQuestions(0);
            newUser.setScore(0);
            newUser.setRank(0);
            newUser.setCreatedAt(new Timestamp(System.currentTimeMillis()));

            // 插入用户到数据库
            try {
                int insertResult = userMapper.insert(newUser);
                if (insertResult <= 0) {
                    throw new BusinessException(500, "用户创建失败");
                }
            } catch (BusinessException e) {
                throw e;
            } catch (Exception e) {
                throw new BusinessException(500, "用户创建异常: " + e.getMessage());
            }

            // 重新查询用户获取完整信息（包括自动生成的userId）
            User createdUser = userMapper.selectByUsername(userDTO.getUsername());
            if (createdUser == null) {
                throw new BusinessException(500, "用户创建成功但无法获取用户信息");
            }

            // 生成 JWT 令牌
            String token = jwtTokenProvider.generateToken(createdUser);

            // 构建登录响应
            LoginDTO loginResponse = setLoginDTO(userDTO.getUsername(), createdUser, token);

            return Response.success("注册成功", loginResponse);

        } catch (BusinessException e) {
            // 业务异常直接抛出，由全局异常处理器处理
            throw e;
        } catch (Exception e) {
            // 其他异常包装为业务异常
            throw new BusinessException(500, "注册失败: " + e.getMessage());
        }
    }

    //登录和注册成功后都需要返回几乎相同的 LoginDTO 结构，提取成方法避免重复
    private static LoginDTO setLoginDTO(String userName, User user, String token) {
        UserDTO responseUser = new UserDTO();
        responseUser.setUsername(userName);
        responseUser.setNickname(user.getNickname());
        responseUser.setRank(user.getRank());
        responseUser.setScore(user.getScore());
        responseUser.setUserId(user.getUserId());
        responseUser.setAvatarUrl(user.getAvatarUrl());
        responseUser.setCorrectQuestions(user.getCorrectQuestions());
        responseUser.setConsecutiveDays(user.getConsecutiveDays());

        // 构建jwt登录响应
        LoginDTO loginResponse = new LoginDTO();
        loginResponse.setToken(token);
        loginResponse.setTokenType("Bearer");
        loginResponse.setExpiresIn(TOKEN_EXPIRE_TIME); // 24小时
        loginResponse.setUser(responseUser);
        return loginResponse;
    }
}